<?php

namespace app\command;

use support\Db;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class Migration extends Command
{
    protected static $defaultName = 'make:migration';
    protected static $defaultDescription = 'Make database migration';
    protected ?string $connection = null;

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, 'migration name of make');
        $this->addOption('connection', null, InputOption::VALUE_OPTIONAL, 'db connection',"default");
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        $this->connection = $input->getOption('connection');

        if (empty($name)) {
            $output->writeln('<error>name is required.</error>');
            return self::INVALID;
        }
        $this->runMakeMigration($name);
        $output->writeln('<info>success!</info>');
        return self::SUCCESS;
    }

    protected function getSchemaBuilder(): \Illuminate\Database\Schema\Builder
    {
        return Db::connection($this->connection)->getSchemaBuilder();
    }

    protected function runMakeMigration(string $name)
    {
        $file = base_path('database/migrations/'.date('Y_m_d_His_').$name.'.php');
        touch($file);
        file_put_contents($file, <<<EOF
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration {
    
    protected \$connection = "{$this->connection}";

    public function up(): void
    {
        \support\Db::schema()->create('',function (Blueprint \$table){
            \$table->increments('id');

            \$table->timestamps();
        });
    }

    public function down(): void
    {
        \support\Db::schema()->dropIfExists('');
    }
};
EOF
        );
    }

}